package org.dataone.dataUsage;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

public class DataCache {
	private static long CACHE_EXPIRATION_PERIOD = 60000 * 720; // cache for 12
																// hours

	private static ArrayList<MonthlyMetric> CNArray = new ArrayList<MonthlyMetric>();
	private static Map<String, ArrayList<MonthlyMetric>> MNMap = new HashMap<String, ArrayList<MonthlyMetric>>();

	private static long CNCacheTimestamp = 0;
	private static long MNCacheTimestamp = 0;

	public static final DataCache INSTANCE = new DataCache();

	private DataCache() {

	}

	public ArrayList<MonthlyMetric> getCNDataMap(String baseURL) {
		if (CNtimeToRefresh()) {
			try {
				CNArray = refreshCNMap(baseURL);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return CNArray;
	}
	public Map<String, ArrayList<MonthlyMetric>> getMNDataMap(String baseURL) {
		if (MNtimeToRefresh()) {
			try {
				MNMap = refreshMNMap(baseURL);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return MNMap;
	}
	/**
	 * This method is to cache data for CN figure display. Returns an ArrayList
	 * of 24months' Coordinating Nodes metric.
	 * 
	 * @param baseURL
	 *            the Coordinating Node Server URL
	 */
	private synchronized ArrayList<MonthlyMetric> refreshCNMap(String baseURL) {
		ArrayList<MonthlyMetric> result = new ArrayList<MonthlyMetric>();
		try {
			CNodeMetric c = new CNodeMetric();
			c.setCN_URL(baseURL);
			result = c.getCNDownloadMetricByMonth(24);

		} catch (Exception sf) {
			sf.printStackTrace();
		}
		CNCacheTimestamp = System.currentTimeMillis();
		return result;
	}
	/**
	 * This method is to cache data for MN figure display. Returns a Map with
	 * each member node name.
	 * 
	 * @param baseURL
	 *            the Coordinating Node Server URL
	 */
	private synchronized Map<String, ArrayList<MonthlyMetric>> refreshMNMap(
			String baseURL) {
		Map<String, ArrayList<MonthlyMetric>> freshMap = new HashMap<String, ArrayList<MonthlyMetric>>();
		try {
			MNodeMetric m = new MNodeMetric();
			m.setCN_URL(baseURL);
			ArrayList<String> mnode = new ArrayList<String>();
			mnode = m.getMNodeList();
			for (int i = 0; i < mnode.size(); i++) {
				ArrayList<MonthlyMetric> temp = new ArrayList<MonthlyMetric>();
				temp = m.getMNDownloadMetricByMonth(mnode.get(i), 24);
				freshMap.put(mnode.get(i), temp);
			}

		} catch (Exception sf) {
			sf.printStackTrace();
		}
		MNCacheTimestamp = System.currentTimeMillis();
		return freshMap;
	}
	private boolean CNtimeToRefresh() {
		return CNCacheTimestamp + CACHE_EXPIRATION_PERIOD < System
				.currentTimeMillis();
	}
	private boolean MNtimeToRefresh() {
		return MNCacheTimestamp + CACHE_EXPIRATION_PERIOD < System
				.currentTimeMillis();
	}
}
